const app = getApp()
const { processListImages } = require('../../utils/image')
const request = require('../../utils/request.js');
Page({
  data: {
    currentStatus: '',
    postList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false
  },

  onLoad() {
    this.loadPostList()
  },

  onShow() {
    if(app.globalData.needRefresh) {
      this.setData({
        currentStatus: '',
        postList: [],
        page: 1,
        hasMore: true
      }, () => {
        this.loadPostList()
      })
      app.globalData.needRefresh = false
    }
  },

  // 加载发布列表
  loadPostList() {
    if (this.data.loading || !this.data.hasMore) return

    this.setData({ loading: true })

    // 调用后端API获取发布列表
    return new Promise((resolve, reject) => {
      // 构建请求参数
      const params = {
        page: this.data.page,
        pageSize: this.data.pageSize,
        status: this.data.currentStatus
      }
      request.request({
        url: `${app.globalData.baseUrl}/api/residues/user/residues`,
        method: 'GET',
        data: params,
        header: {
          'Authorization': `Bearer ${app.getGlobalToken()}`
        },
        success: (res) => {
          const { list, total } = res.data.data

          // 使用工具函数处理图片URL
          const processedList = processListImages(list)

          this.setData({
            postList: [...this.data.postList, ...processedList],
            hasMore: this.data.postList.length + processedList.length < total,
            loading: false
          })
          resolve()
        },
        fail: reject
      })
    })
  },

  // 切换状态标签
  switchStatus(e) {
    const status = e.currentTarget.dataset.status
    if (status === this.data.currentStatus) return

    this.setData({
      currentStatus: status,
      postList: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadPostList()
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      postList: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadPostList()
      wx.stopPullDownRefresh()
    })
  },

  // 上拉加载更多
  onReachBottom() {
    this.setData({
      page: this.data.page + 1
    }, () => {
      this.loadPostList()
    })
  },

  // 编辑发布
  editPost(e) {
    const postId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/supply/publish/publish?id=${postId}`
    })
  },

  // 下架商品
  cancelPost(e) {
    const postId = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确定要下架该商品吗？',
      success: (res) => {
        if (res.confirm) {
          request.request({
            url: `${app.globalData.baseUrl}/api/residues/${postId}/cancel`,
            method: 'POST',
            header: {
              'Authorization': `Bearer ${app.getGlobalToken()}`
            },
            success: () => {
              wx.showToast({
                title: '商品已下架',
                icon: 'success'
              })
              this.setData({
                postList: [],
                page: 1,
                hasMore: true
              })
              this.loadPostList()
            }
          })
        }
      }
    })
  },

  // 删除发布
  deletePost(e) {
    const postId = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: (res) => {
        if (res.confirm) {
          request.request({
            url: `${app.globalData.baseUrl}/api/residues/${postId}`,
            method: 'delete',
            header: {
              'Authorization': `Bearer ${app.getGlobalToken()}`
            },
            success: () => {
              wx.showToast({
                title: '已删除',
                icon: 'success'
              })
              this.setData({
                postList: [],
                page: 1,
                hasMore: true
              })
              this.loadPostList()
            }
          })
        }
      }
    })
  },

  // 发布新内容
  goToPublish() {
    wx.navigateTo({
      url: '/pages/supply/publish/publish'
    })
  },

  // 跳转到详情页
  goToDetail: function (e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/supply/detail/detail?id=${id}`
    })
  },
}) 